from email import policy
from email.parser import BytesParser


# 解析eml文件，返回HTML内容
def parse_eml(file_path):
    with open(file_path, 'rb') as f:
        msg = BytesParser(policy=policy.default).parse(f)

    # 需要邮件其他信息，可以添加到mail_info字典中
    # mail_info = {'subject': msg['subject'], 'from': msg['from'],
    #              'to': msg['to'], 'date': msg['date'], 'body': None}

    target_part = msg
    if msg.is_multipart():
        for part in msg.walk():
            # print(part.get_charset())
            if part.get_content_type() == "text/html":
                target_part = part
                break

    try:
        return target_part.get_payload(decode=True).decode('utf-8')
    except UnicodeDecodeError:
        return target_part.get_payload(decode=True).decode('gbk')


# 保存正文到文件
def write_eml_to_html(eml_file):
    output_file = eml_file.replace('.eml', '.html')
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(parse_eml(eml_file))


from bs4 import BeautifulSoup
from chardet import detect


def read_html_table(html_content):
    """
    读取HTML文件中的表格数据，并按行和列提取内容。
    :param html_content: HTML文件内容
    :return: 包含表格数据的列表
    """

    soup = BeautifulSoup(html_content, 'html.parser')
    target_tag = soup.find('span', {'id': 'fixBand29'})

    if target_tag:
        target_tag = target_tag.find('table')

    else:
        target_tag = soup.find('tbody', {'id': 'repayList'}).find_parent('table')

    if not target_tag:
        return "未找到目标标签"

    # 查找所有叶子<tr>标签（不包含嵌套<table>的<tr>）
    leaf_trs = []
    for tr in target_tag.find_all('tr'):
        if not tr.find('table'):
            leaf_trs.append(tr)

    def empty_list(l):
        if not l or all(not single_str for single_str in l):
            return True
        return False

    # 提取叶子<tr>标签内容
    leaf_data = []
    for tr in leaf_trs:
        cells = [cell.get_text(strip=True).replace('\xa0', '') for cell in tr.find_all(['th', 'td'])]
        if empty_list(cells):
            continue
        leaf_data.append(cells)

    return leaf_data


def write_html_to_txt(html_file_addr):
    # 检测文件编码
    with open(html_file_addr, 'rb') as html_file:
        raw_data = html_file.read()
        encoding = detect(raw_data)['encoding']

    # 动态解码文件内容
    with open(html_file_addr, 'r', encoding=encoding) as html_file:
        html_content = html_file.read()

    table_data = read_html_table(html_content)
    txt_file_addr = html_file_addr.replace('.html', '.txt')
    with open(txt_file_addr, 'w') as txt_file:
        for row in table_data:
            txt_file.write(f"{row}\n")
